package com.mf.morefun.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.TimedMetaData;
import android.media.TimedText;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.format.DateUtils;
import android.util.Log;

import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.GrindingEarsBean;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MusicService extends Service{
    private static final File PATH = Environment.getExternalStorageDirectory();// 获取SD卡总目录。
    public List<GrindingEarsBean> musicList = new ArrayList<>();
    public MediaPlayer player; // 定义多媒体对象
    public int songNum; // 当前播放的歌曲在List中的下标,flag为标致
    public String songName; // 当前播放的歌曲名
    private Context mContext;
    //写一个线程来加载网络音乐
    private Thread mThread = null;
    public final IBinder binder = new MyBinder();
    public class MyBinder extends Binder {
        public MusicService getService(List<GrindingEarsBean> mMusicList, Context context) {
            musicList.addAll(mMusicList);
            mContext = context;
            return MusicService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        stop();
        super.onDestroy();
    }

    class MusicFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3"));//返回当前目录所有以.mp3结尾的文件
        }
    }

    public void setMusicList(List<GrindingEarsBean> mMusicList){
        if (null != mMusicList && mMusicList.size() > 0){
            musicList.clear();
            musicList.addAll(mMusicList);
        }
    }

    public MusicService() {
        super();
        player = new MediaPlayer();
    }

//    public MusicService(List<GrindingEarsBean> musicList, Context mContext) {
//        super();
//        player = new MediaPlayer();
//        this.musicList = musicList;
//        this.mContext = mContext;
//    }

    public void setPlayName(String dataSource) {
        File file = new File(dataSource);//假设为D:\\mm.mp3
        String name = file.getName();//name=mm.mp3
        int index = name.lastIndexOf(".");//找到最后一个.
        songName = name.substring(0, index);//截取为mm
    }

    public void play() {
        if (null != mThread && mThread.isAlive()){
            stop();
            mThread.interrupt();
            mThread = null;
        }
        playThread();
    }

    private void playThread(){
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                playMusic();
            }
        });
        mThread.start();
    }

    private void playMusic(){
        try {
            if (null == player){
                player = new MediaPlayer();
            }
            player.reset(); //重置多媒体
            String dataSource = musicList.get(songNum).getMfAudio().getAddress();//得到当前播放音乐的路径
            setPlayName(dataSource);//截取歌名
            // 指定参数为音频文件
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(mContext, Uri.parse(dataSource));//为多媒体对象设置播放路径
//            player.prepare();//准备播放
            player.prepareAsync();
            //setOnCompletionListener 当当前多媒体对象播放完成时发生的事件
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer arg0) {
                    EventMessageBean eventMessageBean = new EventMessageBean();
                    eventMessageBean.setNum(0);
                    eventMessageBean.setType(0);
                    eventMessageBean.setProgress(0);
                    EventBus.getDefault().post(eventMessageBean);
                }
            });
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    MoreFunApplication.isOut = false;
                    player.start();//开始播放
                    EventMessageBean eventMessageBean = new EventMessageBean();
                    eventMessageBean.setNum(mp.getDuration());
                    eventMessageBean.setType(2);
                    eventMessageBean.setProgress(0);
                    EventBus.getDefault().post(eventMessageBean);
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    MoreFunApplication.isOut = true;
                    EventMessageBean eventMessageBean = new EventMessageBean();
                    eventMessageBean.setNum(0);
                    eventMessageBean.setType(1);
                    eventMessageBean.setProgress(0);
                    eventMessageBean.setFileName(what + "");
                    eventMessageBean.setTime(extra);
                    EventBus.getDefault().post(eventMessageBean);
                    return true;
                }
            });
        } catch (Exception e) {
            MoreFunApplication.isOut = true;
            EventMessageBean eventMessageBean = new EventMessageBean();
            eventMessageBean.setNum(0);
            eventMessageBean.setType(1);
            eventMessageBean.setProgress(0);
            eventMessageBean.setFileName(e.getMessage());
            EventBus.getDefault().post(eventMessageBean);
        }
    }

    //继续播放
    public  void goPlay(){
        int position = getCurrentProgress();
        player.seekTo(position);//设置当前MediaPlayer的播放位置，单位是毫秒。
        try {
            player.prepare();//  同步的方式装载流媒体文件。
        } catch (Exception e) {
            e.printStackTrace();
        }
        player.start();
    }
    // 获取当前进度
    public int getCurrentProgress() {
        if (player != null & player.isPlaying()) {
            return player.getCurrentPosition();
        } else if (player != null & (!player.isPlaying())) {
            return player.getCurrentPosition();
        }
        return 0;
    }

    public void next() {
        songNum = songNum == musicList.size() - 1 ? 0 : songNum + 1;
        play();
    }

    public void last() {
        songNum = songNum == 0 ? musicList.size() - 1 : songNum - 1;
        play();
    }
    // 暂停播放
    public void pause() {
        if (player != null && player.isPlaying()){
            player.pause();
        }
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
            try {
                mThread.sleep(350);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            player.reset();
            player.release();
            player = null;
        }
    }
}


